from django.http import HttpResponse
from django.shortcuts import render
from .models import Publisher, Book


# Create your views here.

def publisher_add(request):
    Publisher.objects.create(name='publisher1', address='合肥')
    return HttpResponse("publisher add  ok")


def book_add(request):
    book = Book(name='book3', price=20, publisher_id=2)
    book.save()
    return HttpResponse("book add  ok")


def book_delete(request):
    Book.objects.filter(id=2).delete()
    return HttpResponse("book delete  ok")


def publisher_delete(request):
    Publisher.objects.filter(id=2).delete()
    return HttpResponse("publisher delete  ok")


def book_select(request):
    book = Book.objects.filter(id=5).first()
    print(book.name, book.price, book.publisher_id)
    # 书本对应出版社的信息  正向
    publisher_name = book.publisher.name
    publisher_address = book.publisher.address
    print(publisher_name, publisher_address)
    return HttpResponse("book select  ok")


def publisher_select(request):
    publisher = Publisher.objects.filter(id=2).first()
    print(publisher.name, publisher.address)
    # 出版社出版的所有图书信息  反向关联  多本书  %2%
    books = publisher.book_set.filter(name__contains='2')
    for book in books:
        print(book.name, book.price, book.publisher_id)
    return HttpResponse("publisher select  ok")
